<?php
namespace app\controller;


use app\common\weixin;
use app\model\AgentCardWalletLog;
use app\model\AxList;
use app\model\CardList;
use app\model\OrderList;
use app\model\RechargeCardLog;
use app\model\UserList;
use app\model\WalletLog;
use commen\axsms;
use commen\ebjyd;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Log;


class Index extends CommonController
{
    public function index()
    {

//        $menu_list = [];
//        foreach ($this->menu_list as $key=>$val)
//        {
//            if(in_array($val["id"],$this->admin_menu_list)||in_array("all",$this->admin_menu_list))
//            {
//                $menu_list[] = $val;
//            }
//        }
//        $menu_list = array_to_tree($menu_list);
//
//
//        $this->assign("menu_list",$menu_list);
//        print_r(bjphbj::recharge(1,"1000113300016631854","D1801051553378370358"));
//        print_r(bjphbj::query("D1801051553378370358"));
        $this->assign("page_title","欢迎登录连连科技加油卡平台");
        return $this->fetch();
    }
    function onlinesms()
    {
        try
        {
            $AxSms = new \app\model\AxSms();
            $RechargeCardLog = new \app\model\RechargeCardLog();
            $RechargeCardList = new \app\model\RechargeCardList();
            $AxList = new AxList();
            $OrderList = new OrderList();
            $result = axsms::get_sms_notify();
            if($result["error"] == 1)
            {
                Log::error(json_encode($result));
            }else{
                $data = $result["data"];
                $telX = $data["telX"];
                $smscontent = $data["smscontent"];
                try{
                    $query = $AxSms->insert($data);
                }catch (\Exception $e)
                {
                    $query = false;
                }
                if(!$query)
                {
                    Log::error("插入数据库失败");
                    Log::error(json_encode($result));
                }
                $log_info = [];
                $status = 0;
                $RechargeCardListStatus = 0;
                if(preg_match("/充值卡卡密\[([0-9]+?)\]验证失败/",$smscontent,$match))
                {
                    $card_pwd = $match[1];
                    $log_info = $RechargeCardLog->where(["telX" => $telX, "card_pwd" => $card_pwd, "status" => 1])->find();
                    $status = 3;
                    $RechargeCardListStatus = 3;
                }elseif(preg_match("/您尾号为\s?([0-9]+?)的加油卡.*?金额([0-9]+?)元/",$smscontent,$match)){
                    $card_no_postfix= $match[1];
                    $money = intval($match[2])*10000;
                    $log_info = $RechargeCardLog->where(["telX" => $telX, "money" => $money,"card_no"=>["like","%".$card_no_postfix], "status" => 1])->find();
                    $status = 2;
                    $RechargeCardListStatus = 2;
                }elseif(preg_match("/\[([0-9]+?)\]充值失败/",$smscontent,$match)){
                    $card_no = $match[1];
                    $log_info = $RechargeCardLog->where(["telX" => $telX, "card_no" => $card_no, "status" => 1])->find();
                    $status = 3;
                }
                elseif(preg_match("/加油卡\[([0-9]+?)\]验证失败/",$smscontent,$match)){
                    $card_no = $match[1];
                    $log_info = $RechargeCardLog->where(["telX" => $telX, "card_no" => $card_no, "status" => 1])->find();
                    $status = 3;
                }
                if(!empty($log_info) &&in_array($status,[2,3]))
                {
                    $AxList->where(["telX"=>$telX,"is_use"=>1])->update(["is_use"=>0]);

                    $id= $log_info["id"];
                    $order_no = $log_info["order_no"];
                    $card_pwd = $log_info["card_pwd"];
                    $money = $log_info["money"];
                    $query = $RechargeCardList->where(["card_pwd"=>$card_pwd,"money"=>$money,"status"=>1])->update(["status"=>$RechargeCardListStatus]);
                    if(!$query)
                        \exception("更新充值卡状态失败");
                    $query = $RechargeCardLog->where(["id"=>$id,"card_pwd"=>$card_pwd,"money"=>$money,"status"=>1])->update(["status"=>$status]);
                    if(!$query)
                        \exception("更新充值卡记录状态失败");
                    if($status==3 &&!empty($order_no))
                    {
                        $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>3]);
                        if(!$query)
                        {
                            $this->order_log($order_no,"充值失败，更新记录失败");
                            \exception("充值失败，更新记录失败");
                        }
                        $this->order_log($order_no,"充值卡充值失败:".$smscontent);
//                        if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//                        {
//                            $this->order_log($order_no,"充值卡充值失败，提交订单后续处理失败");
//                            exception("充值卡充值失败，提交订单后续处理失败");
//                        }
                        if(!sendMQQueue("fuel_order_status",$order_no))
                        {
                            $this->order_log($order_no,"充值卡充值失败，提交订单后续处理失败");
                            exception("充值卡充值失败，提交订单后续处理失败");
                        }

                    }elseif($status==2 &&!empty($order_no))
                    {

                        $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->setInc("supply_basic_price",$money);
                        if(!$query)
                        {
                            $this->order_log($order_no,"充值成功，累加金额失败:".$money);
                            \exception("充值成功，累加金额失败:".$money);
                        }
                        $last_price = $OrderList->where(["order_no"=>$order_no,"status"=>1])->value("`basic_price`-`supply_basic_price`");
                        if($last_price == 0)
                        {
                            $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>2]);
                            if(!$query)
                            {
                                $this->order_log($order_no,"充值成功，更新记录失败");
                                \exception("充值成功，更新记录失败");
                            }
                            $this->order_log($order_no,"充值卡充值成功:".$smscontent);
//                            if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//                            {
//                                $this->order_log($order_no,"充值卡充值成功，提交订单后续处理失败");
//                                exception("充值卡充值成功，提交订单后续处理失败");
//                            }
                            if(!sendMQQueue("fuel_order_status",$order_no))
                            {
                                $this->order_log($order_no,"充值卡充值成功，提交订单后续处理失败");
                                exception("充值卡充值成功，提交订单后续处理失败");
                            }
                        }else{
                            $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>0]);
                            if(!$query)
                            {
                                $this->order_log($order_no,"充值成功，更新记录失败");
                                \exception("充值成功，更新记录失败");
                            }
                            $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值:".$smscontent);
//                            if(!sendQueue("app\job\Orders::order_recharge",[$order_no]))
//                            {
//                                $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
//                                exception("充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
//                            }
                            if(!sendMQQueue("fuel_order_recharge",$order_no))
                            {
                                $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
                                exception("充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
                            }
                        }
                    }
                }

//            if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//            {
//                exception("提交订单后续处理失败");
//            }
            }
        }catch (\Exception $e)
        {
            Log::error(json_encode($e));
        }

        echo json_encode(["code"=>0,"message"=>"success"]);
    }
    function home()
    {
        $this->assign("page_title","欢迎登录连连科技加油卡平台");
        return $this->fetch();
    }
    function test1(){

//        $str = "充值卡卡密[34989945785229731745]验证失败,请重新发送充值短信!【中国石化】";
//        $str = "您尾号为 787707的加油卡于 07月13日 17时27分充值成功,金额50元,订单号:2518071317276052【中国石化】";
//        if(preg_match("/\[([0-9]+?)\]验证失败/",$str,$match))
//        {
//            $card_pwd = $match[1];
//        }elseif(preg_match("/您尾号为\s?([0-9]+?)的加油卡.*?金额([0-9]+?)元/",$str,$match)){
//            print_r($match);
//        }
        $AxSms = new \app\model\AxSms();
        $RechargeCardLog = new \app\model\RechargeCardLog();
        $RechargeCardList = new \app\model\RechargeCardList();
        $AxList = new AxList();
        $OrderList = new OrderList();
        $smscontent = "加油卡[1000113400003787707]充值失败!【中国石化】";
        $telX = "15669220639";
        try{
            $log_info = [];
            $status = 0;
            if(preg_match("/充值卡卡密\[([0-9]+?)\]验证失败/",$smscontent,$match))
            {
                $card_pwd = $match[1];
                $log_info = $RechargeCardLog->where(["telX" => $telX, "card_pwd" => $card_pwd, "status" => 1])->find();
                $status = 3;
            }elseif(preg_match("/您尾号为\s?([0-9]+?)的加油卡.*?金额([0-9]+?)元/",$smscontent,$match)){
                $card_no_postfix= $match[1];
                $money = intval($match[2])*10000;
                $log_info = $RechargeCardLog->where(["telX" => $telX, "money" => $money,"card_no"=>["like","%".$card_no_postfix], "status" => 1])->find();
                $status = 2;
            }elseif(preg_match("/\[([0-9]+?)\]充值失败/",$smscontent,$match)){
                $card_no = $match[1];
                $log_info = $RechargeCardLog->where(["telX" => $telX, "card_no" => $card_no, "status" => 1])->find();
                $status = 3;
            }
            elseif(preg_match("/加油卡\[([0-9]+?)\]验证失败/",$smscontent,$match)){
                $card_no = $match[1];
                $log_info = $RechargeCardLog->where(["telX" => $telX, "card_no" => $card_no, "status" => 1])->find();
                $status = 3;
            }
            if(!empty($log_info) &&in_array($status,[2,3]))
            {
                $AxList->where(["telX"=>$telX,"is_use"=>1])->update(["is_use"=>0]);

                $id= $log_info["id"];
                $order_no = $log_info["order_no"];
                $card_pwd = $log_info["card_pwd"];
                $money = $log_info["money"];
                $query = $RechargeCardList->where(["card_pwd"=>$card_pwd,"money"=>$money,"status"=>1])->update(["status"=>$status]);
                if(!$query)
                    \exception("更新充值卡状态失败");
                $query = $RechargeCardLog->where(["id"=>$id,"card_pwd"=>$card_pwd,"money"=>$money,"status"=>1])->update(["status"=>$status]);
                if(!$query)
                    \exception("更新充值卡记录状态失败");
                if($status==3 &&!empty($order_no))
                {
                    $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>3]);
                    if(!$query)
                    {
                        $this->order_log($order_no,"充值失败，更新记录失败");
                        \exception("充值失败，更新记录失败");
                    }
                    $this->order_log($order_no,"充值卡充值失败:".$smscontent);
//                    if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//                    {
//                        $this->order_log($order_no,"充值卡充值失败，提交订单后续处理失败");
//                        exception("充值卡充值失败，提交订单后续处理失败");
//                    }
                    if(!sendMQQueue("fuel_order_status",$order_no))
                    {
                        $this->order_log($order_no,"充值卡充值失败，提交订单后续处理失败");
                        exception("充值卡充值失败，提交订单后续处理失败");
                    }

                }elseif($status==2 &&!empty($order_no))
                {

                    $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->setInc("supply_basic_price",$money);
                    if(!$query)
                    {
                        $this->order_log($order_no,"充值成功，累加金额失败:".$money);
                        \exception("充值成功，累加金额失败:".$money);
                    }
                    $last_price = $OrderList->where(["order_no"=>$order_no,"status"=>1])->value("`basic_price`-`supply_basic_price`");
                    if($last_price == 0)
                    {
                        $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>2]);
                        if(!$query)
                        {
                            $this->order_log($order_no,"充值成功，更新记录失败");
                            \exception("充值成功，更新记录失败");
                        }
                        $this->order_log($order_no,"充值卡充值成功:".$smscontent);
//                        if(!sendQueue("app\job\Orders::order_notify_ext",[$order_no]))
//                        {
//                            $this->order_log($order_no,"充值卡充值成功，提交订单后续处理失败");
//                            exception("充值卡充值成功，提交订单后续处理失败");
//                        }
                        if(!sendMQQueue("fuel_order_status",$order_no))
                        {
                            $this->order_log($order_no,"充值卡充值成功，提交订单后续处理失败");
                            exception("充值卡充值成功，提交订单后续处理失败");
                        }
                    }else{
                        $query = $OrderList->where(["order_no"=>$order_no,"status"=>1])->update(["status"=>0]);
                        if(!$query)
                        {
                            $this->order_log($order_no,"充值成功，更新记录失败");
                            \exception("充值成功，更新记录失败");
                        }
                        $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值:".$smscontent);
//                        if(!sendQueue("app\job\Orders::order_recharge",[$order_no]))
//                        {
//                            $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
//                            exception("充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
//                        }
                        if(!sendMQQueue("fuel_order_recharge",$order_no))
                        {
                            $this->order_log($order_no,"充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
                            exception("充值卡充值成功,剩余金额:".$money.",再次充值提交失败");
                        }

                    }
                }
            }
        }catch (\Exception $e)
        {
        }


    }
    function test()
    {
//        $result = ebjyd::get_cards(2,10);
//        print_r($result);
//        $telX="17156682509";
//        $weixin = new weixin();
//        $pay_order_no = "P1808121105026284212";
//        $total_money = 1920000;
//        $t_money = 1920000;
//
//        $query = $weixin->RefundOrder($pay_order_no,$total_money/100,$t_money/100);
//        if(!$query)
//            $this->E("退款失败");
//        $result = axsms::bind("17156682509","15669220639");
//        if($result["error"] == 0)
//        {
//            $subid = $result["data"]["subid"];
//            echo $subid;
//        }

//        $result = axsms::unbind("70fb08dfa9f94cf6bb1432f65771b72d");
//        if($result)
//        $result = axsms::sms("708657822da64402adc05552ed286caa","18516507835","DS05-1000113400003787707#34989945785229731745");
//        $result = axsms::query_bind("70fb08dfa9f94cf6bb1432f65771b72d");
        $result = axsms::sms("708657822da64402adc05552ed286caa","18512520188","DS05-1000113400003787707#34989945785229731745");
//        $weixin = new weixin();
//        $result = $weixin->sendText("oqlnwt5XhZdQCV3NeJ4hwlcQ9e8I","test text");
//        print_r($result);
//        subid = "70fb08dfa9f94cf6bb1432f65771b72d"
    }
    function bind_ax()
    {
        $id = 1;
        $AxList = new AxList();
        try {
            $info = $AxList->where(["id" => $id, "status" => 0])->find();
            if(empty($info))
                exception("没有这条数据");
            $query = $AxList->where(["id" => $id, "status" => 0])->update(["status"=>1]);
            if(!$query)
                exception("已经提交绑定");
            $telA = $info["telA"];
            $telX = $info["telX"];
            $areacode = $info["areacode"];
            $name = $info["name"];
            $cardno = $info["cardno"];
            $result = axsms::bind($telA,$telX,$areacode,$name,$cardno);
            $request_data = $result["request_data"];
            $response_data = $result["response_data"];
            if($result["error"] == 0)
            {
                $subid = $result["data"]["subid"];
                $query = $AxList->where(["id" => $id, "status" => 1])->update([
                    "status"=>2,
                    "subid"=>$subid,
                    "request_data"=>$request_data,
                    "response_data"=>$response_data
                ]);
                if(!$query)
                    exception("绑定成功更新失败");
            }else{
                $query = $AxList->where(["id" => $id, "status" => 1])->update([
                    "status"=>3,
                    "request_data"=>$request_data,
                    "response_data"=>$response_data
                ]);
                if(!$query)
                    exception("绑定失败更新失败");
                exception($result["error_info"]);
            }
            echo "true";
        } catch (\Exception $e) {
            echo "fail";
        }
    }

    function delivery_order()
    {
        $OrderList = new OrderList();
        try {
            $order_list = $OrderList->alias("ol")->where(["ol.delivery_status" => 2])->select();
            foreach($order_list as $info)
            {
                $order_no = $info["order_no"];
                if(!empty($info["express_no"]))
                {
                    $express_no = preg_replace("# #","",$info["express_no"]);
                    $express_name = trim($info["express_name"]);
                    $url = "http://baidu.kuaidi100.com/query";
                    $corp_code = "";
                    if(strpos($express_name,"韵达") !== false)
                    {
                        $corp_code = "yunda";
                    }elseif(strpos($express_name,"顺丰") !== false)
                    {
                        $corp_code = "shunfeng";
                    }elseif(strpos($express_name,"申通") !== false)
                    {
                        $corp_code = "shentong";
                    }elseif(strpos($express_name,"圆通") !== false)
                    {
                        $corp_code = "yuantong";
                    }elseif(strpos($express_name,"中通") !== false)
                    {
                        $corp_code = "zhongtong";
                    }elseif(strpos($express_name,"EMS") !== false)
                    {
                        $corp_code = "ems";
                    }
                    if($corp_code)
                    {
                        $delivery_list_obj = curl_url($url,[],"type=".$corp_code."&postid=".$express_no."&id=4&valicode=&temp=".NOW_TIME);
                        if(!empty($delivery_list_obj) &&$delivery_list_obj["code"] == 200)
                        {
                            $info["delivery_list"] = json_decode($delivery_list_obj["body"],true);
                            if($info["delivery_list"]["status"] =="200" &&$info["delivery_list"]["state"] =="3" &&$info["delivery_list"]["nu"] == $express_no)
                            {
                                $query = $OrderList->where(["delivery_status"=>2,"order_no"=>$order_no])->update(["delivery_status"=>3]);
                                if($query)
                                {
                                    $info["delivery_status"]  =3;
                                }
                            }
                        }
                    }
//                $delivery_list_obj = curl_url("http://www.kuaidi100.com/query?type=yunda&postid=".$express_no."&temp=0.".time());
//                if(!empty($delivery_list_obj) &&$delivery_list_obj["code"] == 200)
//                {
//                    $info["delivery_list"] = json_decode($delivery_list_obj["body"],true);
//                }

                }
            }
        } catch (Exception $e) {
        }
    }
    function sends($routing_key,$messageBody)
    {
        try{
//        $exchange = 'router';
            $connection = new AMQPStreamConnection("127.0.0.1", 5672, "admin",  "admin123", "/");
            $channel = $connection->channel();
//        $channel->queue_declare($queue, false, true, false, false);
//        $channel->exchange_declare($exchange, 'direct', false, true, false);
//        $channel->queue_bind($queue, $exchange);
            $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
            $channel->basic_publish($message, "",$routing_key);
            $channel->close();
            $connection->close();
            return true;
        }catch (\Exception $e)
        {

        }
        return false;
    }
    function test2()
    {
        for($i=0;$i<100;$i++)
        {
            $this->sends("mobile_area","test".$i);
        }

    }
}
